<template src="./template.html"></template>
<script>
/* global moment */
import apiUrls from 'common/api-urls'
import checkForm from 'mixins/checkform'
import { validateOrgName } from 'utils/ui-utils'
import { FILE_MIME_TYPE, FUN_IDS_OPTIONS } from 'common/consts'
import { uploadFile } from 'common/common-models'
import { ENABLED_STATUS } from './consts'
import { getCustomerProjectList, addCustomer, updateCustomer, getCustomerById, checkCode } from '../models'

export default {
  data() {
    return {
      resourceUrl: apiUrls.resourceUrl, // 静态资源地址
      FUN_IDS_OPTIONS,
      ENABLED_STATUS,
      fileMimeType: FILE_MIME_TYPE, // 文件上传类型

      id: '',
      isPageLoading: false,
      projectList: [],
      basicForm: {
        companyCode: '',
        companyName: '',
        companyLogo: '',
        companySysName: '',
        funIds: [],
        isLimitNums: '0',
        authCount: '',
        useLimit: '0',
        deadlineTime: '',
        enabled: 0,
        createTime: '',
        createBy: '',
      },
      rules: {
        companyCode: [{ required: true, message: '请输入企业码', trigger: 'change' },
          { validator: this.$validateCode, trigger: 'blur' }],
        companyName: [{ required: true, message: '请输入企业名称', trigger: 'change' },
          { validator: validateOrgName, trigger: 'blur' }],
        companySysName: [{ required: true, message: '请输入系统名称', trigger: 'change' },
          { validator: validateOrgName, trigger: 'blur' }],
        funIds: [{ required: true, message: '请输入授权功能', trigger: 'change' }],
        isLimitNums: [{ required: true, message: '请输入授权人数', trigger: 'change' }],
        useLimit: [{ required: true, message: '请勾选授权期限', trigger: 'blur' },
          { validator: this.$validUseLimit, trigger: 'blur' }],
        enabled: [{ required: true, message: '请输入授权状态', trigger: 'change' }]
      },
    }
  },
  computed: {
    isEdit() {
      return this.$route.name === 'base-manage.org.edit'
    },
    isDetail() {
      return this.$route.name === 'base-manage.org.detail'
    },
  },
  mixins: [
    checkForm
  ],
  watch: {
    'basicForm.useLimit': {
      handler() {
        if (parseInt(this.basicForm.useLimit, 10) === 0) {
          this.basicForm.deadlineTime = ''
        }
      },
      deep: true,
      immediate: true,
    }
  },
  methods: {
    async $validateCode(rule, value, callback) {
      if (/^[A-Za-z|\d]{4,8}$/.test(value)) {
        try {
          if (!this.isEdit) {
            const { data } = await checkCode({ code: value })
            if (data) {
              return callback(new Error('该企业码已存在！'))
            }
          }
          return callback();
        } catch (err) {
          return callback(new Error(err.message || '校验异常'))
        }
      }
      return callback(new Error('请输入4-8位英文或数字'))
    },
    $validUseLimit(rule, value, callback) {
      if (value === '1' && !this.basicForm.deadlineTime) {
        return callback(new Error('请输入授权期限'))
      }
      callback()
    },
    async $handleBgmUrlChange(file) {
      this.isLoading = true
      const params = {
        file: file
      }
      const res = await uploadFile(params)
      this.basicForm.companyLogo = res.data[0].filePath || ''
      this.isLoading = false
    },
    async $getCustomerProjectList() {
      try {
        const res = await getCustomerProjectList()
        this.projectList = res.data || []

        this.basicForm.funIds = Object.keys(this.projectList)
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || '拉取列表异常')
      }
    },
    async $saveForm() {
      const isVaild = await !this.$asyncCheckForm('basicForm')
      if (isVaild) {
        return
      }
      this.isPageLoading = true
      let func = addCustomer
      const params = {
        ...this.basicForm,
        funIds: this.basicForm.funIds.join(','),
        authCount: parseInt(this.basicForm.isLimitNums, 10) === 0 ? 0 : this.basicForm.authCount
      }
      if (this.basicForm.useLimit === '1' && this.basicForm.deadlineTime) {
        params.deadlineTime = moment(this.basicForm.deadlineTime).format('YYYY-MM-DD')
      } else {
        params.deadlineTime = ''
      }
      delete params.isLimitNums
      if (this.$route.params.id) {
        func = updateCustomer
        params.id = this.$route.params.id
      }
      try {
        await func(params)
        this.isPageLoading = false
        this.$message.success('保存企业信息成功')
        this.$router.go(-1)
      } catch (err) {
        this.isPageLoading = false
        this.$message.error(err.message || err.message || '保存企业信息出错')
      }
    },
    async getById() {
      const params = {
        id: this.$route.params.id
      }
      this.isPageLoading = true
      try {
        const res = await getCustomerById(params)
        const data = res.data || {}
        for (const k in this.basicForm) {
          if (data[k] === null || data[k] === undefined) {
            this.basicForm[k] = ''
          } else {
            this.basicForm[k] = data[k]
          }
        }
        if (data.funIds) {
          this.basicForm.funIds = data.funIds.split(',')
        } else {
          this.basicForm.funIds = []
        }
        if (data.authCount === 0) {
          this.basicForm.isLimitNums = '0'
          this.basicForm.authCount = ''
        } else {
          this.basicForm.isLimitNums = '1'
        }
        this.basicForm.createTime = data.createTime ? moment(data.createTime).format('YYYY-MM-DD HH:mm:ss') : ''

        this.isPageLoading = false
      } catch (err) {
        console.log(err)
        this.isPageLoading = false
        this.$message.error(err.message || err.message || '拉取机构详细异常')
      }

    },
  },
  mounted() {
    this.$getCustomerProjectList()
    if (this.$route.params.id) {
      this.id = this.$route.params.id
      this.getById()
    }
  },
};
</script>
